<template>
    <el-card>
        <template #header>
            <div class="card-header">
                <span>轮播图管理</span>
            </div>
        </template>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="id" label="#" />
            <el-table-column prop="title" label="链接标题" />
            <el-table-column prop="picture" label="轮播图片">
                <template #default="scope">
                    <div class="block">
                        <el-avatar shape="square" :size="50" :src="scope.row.picture" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="url" label="跳转地址" />
            <el-table-column prop="target" label="跳转方式" />
            <el-table-column label="排序数字" width='110'>
                <template #default="scope">
                    <el-tag>{{ scope.row.slide_order }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="create_time" label="添加日期" width='180' />

            <el-table-column label="状态">
                <template #default="scope">
                    <el-tag v-if="tableData[scope.$index].usable==1" class="ml-2" type="success">开启</el-tag>
                    <el-tag v-if="tableData[scope.$index].usable==-1" class="ml-2" type="info" plain>禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width='180'>
                <template #default="scope">
                    <el-space>
                        <el-link>
                            <el-button @click="handleOpenDialog(scope.row,scope.$index)" class="edit" type="primary"
                                size="small">
                                编辑
                            </el-button>
                        </el-link>
                        <el-button v-if="tableData[scope.$index].usable==1"
                            @click="handleOff(scope.row.id,scope.$index)" type="primary" size="small" plain>
                            禁用
                        </el-button>

                        <el-button v-if="tableData[scope.$index].usable==-1"
                            @click="handleOpen(scope.row.id,scope.$index)" type="primary" size="small">
                            启用
                        </el-button>
                        <el-button @click="handleRemove(scope.row.id,scope.$index)" size="small" type="danger">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </el-space>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 编辑轮播图片 -->
    <el-dialog v-model="dialogVisible" title="编辑轮播图">

        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">

            <el-form-item prop="picture" label="轮播图片">

                <el-upload action="http://localhost:3001/upload/common/" :data="extra" :headers="headers"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-remove="handleMove()"
                    :on-error="handleUploadError" :show-file-list="false" accept=".jpg,.jpeg,.png"
                    class="avatar-uploader">
                    <img v-if="form.picture" :src="form.picture" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
                <!-- <el-dialog v-model="dialog">
                    <img w-full :src="dialogImageUrl"  />
                </el-dialog> -->
            </el-form-item>

            <el-form-item prop="title" label="标题文字">
                <el-input v-model="form.title" />
            </el-form-item>
            <el-form-item prop="url" label="链接地址">
                <el-input v-model="form.url" />
            </el-form-item>
            <el-form-item label="跳转方式" prop="target">
                <el-radio-group v-model="form.target">
                    <el-radio label="_self">本窗口跳转</el-radio>
                    <el-radio label="_blank">新窗口跳转</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="slide_order" label="显示顺序">
                <el-input v-model="form.slide_order" />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEdit(formRef)">保存</el-button>
            </span>
        </template>

    </el-dialog>
</template>
<script setup>
    // import { UploadProps, UploadUserFile } from 'element-plus'
import { toRefs, reactive, ref, computed, onMounted, onUpdated } from 'vue';
import Extension from '@/api/extension';
import { Plus } from '@element-plus/icons-vue';
// import { fromJSON } from 'postcss';

//获取form表单实例化对象
let formRef = ref();
// import { id } from 'element-plus/es/locale';
// import { ElMessageBox } from 'element-plus';
const dialogVisible = ref(false);
//删除轮播图
// const dialogImageUrl = ref('')
// const dialog = ref(false);

const tableData = ref([]);
let form = ref({ picture: '', title: '', picture: '', target: '', slide_order: '', url: '' ,usable:''});
let current = ref(0);
//打开编辑轮播图弹窗
let handleOpenDialog = (data, i) => {

    // console.log(id)
    dialogVisible.value = true;
    //记录当前索引
    current.value = i;
    //还原表单
    form.value = { ...data };


}

//提取token
let token = sessionStorage.token;
let headers = { Authorization: `Bearer ${token}` };
//附带参数
let extra = { type: 'common' };
const handleAvatarSuccess = ({ status, msg, src }, uploadFile) => {
    //    console.log(response,uploadFile)
    //上传成功
    if (status) {
        //生成图片地址，预览图片
        form.value.picture = src;
        ElMessage.success(msg);
    } else {
        //上传失败 
        ElMessage.error(msg);
    }
}
const handleUploadError = (error, uploadFile) => {
    console.dir(error)
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);

};
const beforeAvatarUpload = (rawFile) => {
    //判断图片格式/^image\/[jepg|png|jpg]$/
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式!!!')
        return false
    }
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}

//获取轮播图列表
async function loadList() {
    let { status, msg, total, data } = await Extension.retation();
    if (status) {
        tableData.value = data;
    }
}
loadList();
// 表单验证规则
const rules = reactive({
    url: [
        { required: true, message: '请输入链接地址！', trigger: 'blur' },

    ],
    slide_order: [
        { required: true, message: '请输入跳转顺序', trigger: 'blur' },
    ],
    picture: [
        { required: true, message: '请放入图片！', trigger: 'blur' },

    ],
    target: [
        { required: true, message: '请选择跳转方式！', trigger: 'change' },
    ],
});
function handleEdit(formEl) {
    // 校验整个表单
    formEl.validate(async (valid, fields) => {
        if (valid) {
            // 通过校验
            let { status, msg, data } = await Extension.edit({ ...form.value });

            if (status) {
                ElMessage.success(msg)
                dialogVisible.value = false;
                //操作DOM       
    
         tableData.value[current.value]={...form.value}
        //  tableData.value.sort(function (a,b){
        //     return (a-b);
        //  })
            } else {

                ElMessage.error(msg)
            }
        }
        else {
            // 校验失败
            console.log('失败字段', fields);
        }
    });
}
//删除轮播图片
function handleMove(id, i) {
//     let UploadProps = (uploadFile, uploadFiles) => {
//   console.log(uploadFile, uploadFiles)
// }
}
//禁用
function handleOff(id, i) {
    ElMessageBox.confirm('确定禁用？', '确认', { type: 'error', cancelButtonText: '取消', confirmButtonText: '确认' })
        .then(async () => {
            //点击确认
            //发送ajax
            let { status, msg } = await Extension.off({ id: id, usable: -1 });
            if (status) {
                tableData.value[i].usable=-1
                ElMessage.success(msg);
            } else {
                //错误提示
                ElMessage.error(msg);
            }
        })
        //取消
        .catch(() => {
            //取消
            ElMessage.info('取消成功');
        });
}
//启用
function handleOpen(id, i) {
    ElMessageBox.confirm('确定开启？', '确认', { type: 'error', cancelButtonText: '取消', confirmButtonText: '确认' })
        .then(async () => {
            //点击确认
            //发送ajax
            let { status, msg } = await Extension.open({ id: id, usable: 1 });
            if (status) {
                ElMessage.success(msg);
                tableData.value[i].usable=1
            } else {
                //错误提示
                ElMessage.error(msg);
            }
        })
        //取消
        .catch(() => {
            //取消
            ElMessage.info('取消成功');
        });
}

//删除操作
function handleRemove(id, i) {
    ElMessageBox.confirm('确定要删除？', '确认删除', { type: 'error', cancelButtonText: '取消', confirmButtonText: '确认' })
        .then(async () => {
            //点击确认
            //发送ajax
            let { status, msg } = await Extension.remove({ id })
            if (status) {
                ElMessage.success(msg);
                //操作DOM
                tableData.value.splice(i, 1);
            } else {
                ElMessage.error(msg);
            }
        })
        //取消
        .catch(() => {
            //取消
            ElMessage.info('取消成功');
        });
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>